package com.business.lgh.naocs.naming.health;

import com.business.lgh.nacos.api.naming.pojo.Instance;
import com.business.lgh.naocs.naming.consistency.KeyBuilder;
import com.business.lgh.naocs.naming.core.ServerMemberManager;
import com.business.lgh.naocs.naming.core.pojo.InstanceWrapper;
import com.business.lgh.naocs.naming.core.pojo.Member;
import com.business.lgh.naocs.naming.core.pojo.ServiceWrapper;
import com.business.lgh.naocs.naming.web.DistroMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lgh
 * @version V1.0
 * @Package com.business.lgh.naocs.naming.health
 * @date 2020/6/25 8:03 下午
 */
@Data
@Slf4j
public class HealthTask implements Runnable {

    private ServiceWrapper service;

    @Autowired
    DistroMapper distroMapper;

    @Autowired
    ServerMemberManager serverMemberManager;

    private HealthTask() {
    }

    public HealthTask(ServiceWrapper service) {
        this.service = service;
    }

    public String taskKey() {
        return KeyBuilder.buildServiceMetaKey(service.getNamespaceId(), service.getName());
    }

    @Override
    public void run() {
        log.info("HealthTask-run");
        String targetServer = distroMapper.getServer(distroMapper.responsible(service.getName()));
        if (StringUtils.isEmpty(targetServer) && !targetServer.contains(serverMemberManager.getLocalAddress())) {
            return;
        }
        List<InstanceWrapper> instances = service.allIPs(true);
        //遍历实例，大于15s
        for (InstanceWrapper instance : instances) {
            if ((System.currentTimeMillis() - instance.getBeatTime()) > TimeUnit.SECONDS.toMillis(15)) {
                if (instance.isHealthy()) {
                    //设置不健康
                    instance.setHealthy(false);
                }
            }
        }

        //遍历实例，大于30s 移除实例
        for (InstanceWrapper instance : instances) {
            if ((System.currentTimeMillis() - instance.getBeatTime()) > TimeUnit.SECONDS.toMillis(30)) {
                //TODO 调用下线接口
            }
        }
    }
}
